<?php

namespace App\Models;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class Announcement extends BaseModel
{
    function getAnnouncement(){
        $result = DB::table('announcement')->orderBy('id','desc')->limit(5)->select('*')->get();
        return ['data' => $result];
    }

    function announcementList($params){
        $limit = array_key_exists('limit',$params) ? $params['limit'] : 30;
        $page = array_key_exists('page',$params) ? $params['page'] - 1 : 0;
        if($page != 0){
            $page = $page * $limit;
        }

        $result = DB::table('announcement')->where('create_time','>=',$params['start'])->where('create_time','<=',$params['end']);
        if (isset($params['title']) && !empty($params['title'])){
            $result->where('title','like','%'.$params['title'].'%');
        }
        if (isset($params['detail']) && !empty($params['detail'])){
            $result->where('detail','like','%'.$params['detail'].'%');
        }
        $count = $result->count();
        $data = $result->orderBy('create_time','DESC')->offset($page)->limit($limit)->select('*')->get();

        foreach ($data as $item){
            $item->user_name = $this->GetUsers($item->user_id)['account'] ?? '';
        }

        return [
            'code' => 200,
            'msg' => '获取成功！',
            'data' => ['count' => $count, 'list' => $data],
        ];
    }
    function announcementAdd($params){
        $insertData = [
            'user_id' => $params['user_id'],
            'title' => $params['title'],
            'detail' => $params['detail'],
            'create_time' => date("Y-m-d H:i:s"),
        ];
        $result = DB::table('announcement')->insertGetId($insertData);
        return ['data' => $result, 'code' => 200, 'msg' => '新增成功！'];
    }
    function announcementUpdate($params){
        $updateDate = [
            'user_id' => $params['user_id'],
            'title' => $params['title'],
            'detail' => $params['detail'],
            'update_time' => date("Y-m-d H:i:s"),
        ];
        $result = DB::table('announcement')->where('id',$params['id'])->update($updateDate);
        return ['data' => $result, 'code' => 200, 'msg' => '更新成功！'];
    }
    function announcementDel($params){
        $result = DB::table('announcement')->whereIn('id', $params['id'])->delete();
        return ['data' => $result, 'code' => 200, 'msg' => '删除成功！'];
    }
}